﻿package sala.components
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import gs.TweenMax;
	
	/**
	 * ...
	 * @author DefaultUser (Tools -> Custom Arguments...)
	 */
	public class HorScroll extends Sprite
	{
		public var mask_mc:Sprite;
		public var content_mc:MovieClip;
		public var horTrack_mc:MovieClip;
		public var horFace_mc:MovieClip;
		
		public var viewPortWidth:int;
		public var viewPortHeight:int;
		
		private var horRange:int;
		private var horScrollRange:int;
		private var duration:Number;
		private var isHorScrolled:Boolean = false;
		public function HorScroll(maskedmc:Sprite, content:MovieClip, horScrollTrack:MovieClip, horScrollFace:MovieClip, duration:Number = 0.7 ) 
		{
			this.mask_mc = maskedmc;
			this.content_mc = content;
			this.content_mc.x = this.mask_mc.x;
			this.horTrack_mc = horScrollTrack;
			this.horFace_mc = horScrollFace;
			viewPortWidth = mask_mc.width;
			viewPortHeight = mask_mc.height;
			this.duration = duration;
			updateScroll();
			this.horFace_mc.addEventListener(MouseEvent.MOUSE_DOWN, horFaceMouseDownHandler);
			this.mask_mc.stage.addEventListener(MouseEvent.MOUSE_UP, horFaceMouseUpHandler);
			this.mask_mc.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
		}
		private function horFaceMouseUpHandler(e:MouseEvent):void 
		{
			isHorScrolled = false;
			horFace_mc.stopDrag();
		}
		private function horFaceMouseDownHandler(e:MouseEvent):void 
		{
			isHorScrolled = true;
			horFace_mc.startDrag(false, new Rectangle(horTrack_mc.x, horTrack_mc.y, horTrack_mc.width - horFace_mc.width, 0));
		}
		public function updateScroll():void {
			horRange = horTrack_mc.width - horFace_mc.width;
			horScrollRange = content_mc.width - mask_mc.width + 1;
		}		
		private function mouseMoveHandler(e:MouseEvent):void 
		{
			if (isHorScrolled) {
				var newX:int = mask_mc.x - ((horFace_mc.x - horTrack_mc.x) / horRange) * horScrollRange;
				TweenMax.to( content_mc, duration, { x: -newX } );
			}
		}
		
		public function setContentPosX(newX:int, duration:Number = 0.5):void {
			if (newX > mask_mc.x) newX = mask_mc.x;
			if (newX < mask_mc.x - (content_mc.width - mask_mc.width)) newX = mask_mc.x - (content_mc.width - mask_mc.width);
			TweenMax.to(this.content_mc, duration, { x: newX } );
			var newHorFaceX:int = this.horTrack_mc.x + ((mask_mc.x - newX) / horScrollRange) * horRange;
			TweenMax.to(this.horFace_mc, duration, { x: newHorFaceX } );
		}
	}
	
}